import Axios from 'axios'
import Config from '../config/app.js'
import {Loading, Notification} from 'element-ui';
import {getToken, isLogin, removeToken} from './dataStorage.js'

import router from '../router/router'

const service = Axios.create({
    baseURL: Config.apiUrl + '/' + Config.apiPrefix,
    headers: {
        'Accept': '*/*',
    },
    timeout: Config.timeout
})
service.defaults.retry = Config.requestRetry;
service.defaults.retryDelay = Config.requestRetryDelay;

service.interceptors.request.use(
    config => {
        if (!config.closeLoading) {
            window.loadingInstance = Loading.service({
                fullscreen: true
            });
        }

        if (isLogin()) {
            config.headers['Access-Token'] = getToken();
        }
        let noParameters = config.url.indexOf('?') == -1;
        return config
    },

    error => {

        Promise.reject(error)
    }
)


service.interceptors.response.use(

    response => { //Grade
        const res = response;
        if (!response.config.closeLoading) {
            window.loadingInstance.close();
        }

        if (res.status !== 200) {
            Notification({
                title: '数据返回出错',
                message: "请稍后重试",
                type: 'warning'
            });
            return Promise.reject('error')
        }
        console.log(res.data);
        if ((response.config).hasOwnProperty('closeInterceptors') && response.config.closeInterceptors) {
            return res.data
        }

        if (res.data.success == 0) {
            Notification({
                title: '提示',
                message: res.data.message,
                type: 'warning'
            });
            return Promise.reject('error');
        }
        if (res.data.success != 1) {
            Notification({
                title: '提示',
                message: res.data.message,
                type: 'warning'
            });
            return Promise.reject('error');
        }

        return res.data.data;
    },

    error => {
        console.log("error:" + error)
        if (error == "Error: Request failed with status code 403" || error == "403") {
            Notification({
                title: '请求失败',
                message: "身份验证失效,请重新登录",
                type: 'warning'
            });
            removeToken();
            router.push("/");
        } else {
            setTimeout(_ => {
                window.loadingInstance.close();
            }, 300)
            Notification({
                title: "请求未响应",
                message: "服务器可能出了点问题",
                type: 'warning'
            });
            return Promise.reject(error) //千万不能去掉，，，否则请求超时会进入到then方法，导致逻辑错误。
        }
    }
)

export default service
